package com.langsin.action;

import com.langsin.service.ProductService;
import com.langsin.service.impl.ProductServiceImpl;
import com.langsin.vo.Product;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

public class ProductInsertAction extends HttpServlet{
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        String pname = request.getParameter("pname");
        String pcode = request.getParameter("pcode");
        String price = request.getParameter("price");
        String ptype = request.getParameter("ptype");
        String pfac = request.getParameter("pfac");
        String desc = request.getParameter("desc");
        String id = request.getParameter("id");
        int result = 0;
        Product product = null;
        ProductService service = new ProductServiceImpl();
        if("".equals(id)){
            id = UUID.randomUUID().toString();
            product = new Product(id,pname,price,pfac,pcode,ptype,desc);
            result = service.insertProduct(product);
        }else{
            product = new Product(id,pname,price,pfac,pcode,ptype,desc);
            result = service.updateProduct(product);
        }

        if(result > 0){
            request.setAttribute("prodDetail",product);
            request.getRequestDispatcher("./productDetail.jsp").forward(request,response);
        }else{
            response.sendRedirect(request.getContextPath()+"/error.jsp");
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
